package com.sinosoft.web.easyui.api;

import cn.com.sinux.spring.commons.SystemConfig;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sinosoft.hydra.um.LoginUser;
import cn.com.sinux.spring.commons.ImageCropHelper;
import cn.com.sinux.spring.commons.PropertyCollection;
import com.sinosoft.hydra.um.constant.BaseConstant;
import com.sinosoft.hydra.um.domain.model.FileInfo;
import cn.com.sinux.spring.exception.BusinessException;
import com.sinosoft.hydra.um.helper.LoggerHelper;
import com.sinosoft.hydra.um.services.FileService;
import com.sinosoft.web.common.FileWebInput;
import cn.com.sinux.spring.json.JsonFilter;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/16.
 */
@Controller
@RequestMapping("api/file")
public class SysFileApi {

    @Autowired
    private FileService fileService;

    /**
     * 上传文件
     *
     * @param loginUser
     * @return true
     */
    @RequestMapping(value = "uploadTempFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadTempFile(LoginUser loginUser, FileWebInput fileWebInput, HttpServletResponse response) throws Exception {
        response.setContentType("text/html; charset=UTF-8");
        String[] fileNames = fileWebInput.getFileNames();
        if (fileNames == null || fileNames.length == 0) {
            throw new BusinessException("zhi.shao.xu.yao.yi.ge.fu.jian");
        }
//        fileWebInput.
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        String fileName = fileWebInput.getMultipartFile(fileNames[0]).getOriginalFilename();
        if (fileName.length() > 50) {
            throw new BusinessException("fu.jian.wen.jian.ming.bu.neng.tai.chang");
        }
//        fileWebInput.get
        FileInfo file = fileService.fileUploadAndPersistence(fileWebInput.getFileInputStream(fileNames[0]),
                fileName, BaseConstant.FileType.FILE_TYPE_TEMP);
        String result = JsonFilter.doPropertyFilter(file, new PropertyCollection()
                .addProperties(FileInfo.class, "attachmentName", "attachment"));
        LoggerHelper.logDebug("上传了文件{}", file.getAttachmentName());
        return new ResponseEntity<String>(result, headers, HttpStatus.OK);
    }


    /**
     * 上传文件方法
     *
     * @param loginUser
     * @param fileWebInput
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @RequestMapping(value = "/uploadForCrop", method = RequestMethod.POST)
    public Object cropUpload(LoginUser loginUser, FileWebInput fileWebInput, HttpServletResponse response) throws Exception {
        response.setContentType("text/html; charset=UTF-8");
        String[] fileNames = fileWebInput.getFileNames();
        if (fileNames == null || fileNames.length == 0) {
            throw new BusinessException("zhi.shao.xu.yao.yi.ge.fu.jian");
        }
        //        fileWebInput.
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        String fileName = fileWebInput.getMultipartFile(fileNames[0]).getOriginalFilename();
        if (fileName.length() > 50) {
            throw new BusinessException("fu.jian.wen.jian.ming.bu.neng.tai.chang");
        }
//        fileWebInput.get
        FileInfo file = fileService.fileUploadAndResize(fileWebInput.getFileInputStream(fileNames[0]),
                fileName, BaseConstant.FileType.FILE_TYPE_TEMP, 400);
        LoggerHelper.logDebug("上传了文件{}", fileName);
        String result = JsonFilter.doPropertyFilter(file, new PropertyCollection()
                .addProperties(FileInfo.class, "attachmentName", "attachment", "width", "height"));
        return new ResponseEntity<String>(result, headers, HttpStatus.OK);
    }

    /**
     * 图片截取
     *
     * @return
     * @throws java.io.IOException
     */
    @RequestMapping(value = "/crop", method = RequestMethod.POST)
    @ResponseBody
    public Object crop(LoginUser loginUser, @RequestParam(value = "path", required = true) String path,
                       final ImageCropHelper imageCropHelper) throws Exception {
        String newPath = fileService.cropImg(path, imageCropHelper);
        return Collections.singletonMap("attachment", newPath);
    }

    /**
     * 上传文件
     *
     * @param loginUser
     * @return true
     */
    @RequestMapping(value = "uploadEditorFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadEditorFile(LoginUser loginUser, FileWebInput fileWebInput, HttpServletResponse response) throws Exception {
        if (!ServletFileUpload.isMultipartContent(fileWebInput.getMultipartRequest())) {
            throw new BusinessException("请选择文件。");
        }
        response.setContentType("text/html; charset=UTF-8");
        String[] fileNames = fileWebInput.getFileNames();
        if (fileNames == null || fileNames.length == 0) {
            throw new BusinessException("zhi.shao.xu.yao.yi.ge.fu.jian");
        }
        String fileName = fileWebInput.getMultipartFile(fileNames[0]).getOriginalFilename();
        if (fileName.length() > 50) {
            throw new BusinessException("fu.jian.wen.jian.ming.bu.neng.tai.chang");
        }
        FileInfo file = fileService.fileUploadAndPersistence(fileWebInput.getFileInputStream(fileNames[0]),
                fileName, BaseConstant.FileType.FILE_TYPE_TEMP);
        //doCrize
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("error", BaseConstant.INTEGER_FALSE);
        results.put("url", fileWebInput.getMultipartRequest().getContextPath() + "/print/" + file.getAttachment());
        LoggerHelper.logDebug("上传了文件{}", fileName);
        return results;
    }

    @RequestMapping(value = "userHeadList", method = RequestMethod.POST)
    @ResponseBody
    public Object userHeadList(HttpServletRequest request){
        File file = new File(SystemConfig.getProperty("trunk.root.path") + "/userHead");
        File[] files = file.listFiles();
        JSONArray list = new JSONArray();
        for (File file1 : files) {
            JSONObject obj = new JSONObject();
            obj.put("id", "/userHead/" + file1.getName());
            obj.put("text", "<img src='"+request.getContextPath()+"/print/userHead/"+file1.getName()+"' style='width: 44px;height: 44px;'>");
            list.add(obj);
        }
        return list;
    }

}
